package cn.com.api.controller;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ibm.icu.math.BigDecimal;

import cn.com.api.entity.ApiAddress;
import cn.com.api.entity.ApiCar;
import cn.com.api.entity.ApiT_goods_topic;
import cn.com.api.entity.ApiT_member;
import cn.com.api.service.ApiAddressService;
import cn.com.api.service.ApiCarService;
import cn.com.api.service.ApiT_goods_topicService;
import cn.com.api.service.ApiT_memberService;
import cn.com.api.service.ApiT_orderService;
import cn.com.api.service.CheckService;
import cn.com.uthink.util.DateTimeUtil;
import cn.com.util.DateUtil;
import cn.com.util.JsonUtil;
import cn.com.util.Util;
import cn.com.util.Utils;

@Controller
@RequestMapping(Utils.SYS_API + "car/")
public class ApiCarController {

	@Autowired
	private ApiCarService apiCarService;
	@Autowired
	private CheckService checkService;
	@Autowired
	private ApiAddressService addressService;
	@Autowired
	private ApiT_memberService memberService;
	@Autowired
	private ApiT_orderService apiT_orderService;
	@Autowired
	private ApiT_goods_topicService goods_topicService;

	private static Logger logger = Logger.getLogger(ApiCarController.class);

	/**
	 * 添加到购物车
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping(value = "add")
	public void addToCard(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 商品goods_id 用户u_id 商品数量count
			String goods_idstr = request.getParameter("goods_id");
			String product_idstr = request.getParameter("product_id");
			String u_id = request.getParameter("u_id");
			String addFlag = request.getParameter("addFlag");
			// String token = request.getParameter("token");
			Map<String, String> params = new HashMap<String, String>();
			params.put("u_id", u_id);
			params.put("goods_id", goods_idstr);
			params.put("product_id", product_idstr);
			params.put("addFlag", addFlag);
			// params.put("token", token);
			params.put("count", "1");
			apiCarService.addCar(params, map);
			/*
			 * if (checkService.checkToken(u_id, token, map) &&
			 * checkService.checkAddCar(params, map)) { // 添加购物车----1元购的校验 if
			 * (apiCarService.checkCarOneGoods(params, map)) {
			 * apiCarService.addCar(params, map); } }
			 */

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.write(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 添加到购物车
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "addCar")
	public void addCar(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 商品goods_id 用户u_id 商品数量count
			String goods_idstr = request.getParameter("goods_id");
			String product_idstr = request.getParameter("product_id");
			String u_id = request.getParameter("u_id");
			String count = request.getParameter("count");
			// String token = request.getParameter("token");
			Map<String, String> params = new HashMap<String, String>();
			params.put("u_id", u_id);
			params.put("goods_id", goods_idstr);
			params.put("product_id", product_idstr);
			params.put("count", count);
			apiCarService.addCar2(params, map);
			/*
			 * //params.put("token", token); if (checkService.checkToken(u_id,
			 * token, map) && checkService.checkAddCar2(params, map)) { //
			 * 添加购物车----1元购的校验 if (apiCarService.checkCarOneGoods(params, map))
			 * { apiCarService.addCar2(params, map); } }
			 */
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.write(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 到购物车-查看
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "goCar")
	public void goCar(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 用户u_id checkService.checkToken(u_id,token,map) &&
			String u_id = request.getParameter("u_id");
			String token = request.getParameter("token");
			// 加city_id
			String city_id = request.getParameter("city_id");
			Map<String, String> params = new HashMap<String, String>();
			params.put("u_id", u_id);
			params.put("token", token);
			params.put("city_id", city_id);
			if (checkService.checkToken(u_id, token, map) && checkService.checkParams(params, map)) {
				// 添加购物车
				apiCarService.goCar(params, map);
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		JSONObject json = JSONObject.fromObject(map);
		out.write(json.toString());
		out.close();
	}

	/**
	 * 删除购物车记录
	 */
	@Transactional
	@RequestMapping(value = "delete")
	public void deleteCar(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			Map<String, String> params = new HashMap<String, String>();
			String u_id = request.getParameter("u_id");
			String token = request.getParameter("token");
			String c_id = request.getParameter("c_id");
			params.put("u_id", u_id);
			params.put("token", token);
			params.put("c_id", c_id);
			if (checkService.checkToken(u_id, token, map) && checkService.checkParams(params, map)) {
				Integer cid = Integer.parseInt(c_id);
				apiCarService.deleteCar(cid);
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "删除成功！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.write(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 批量删除购物车
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "deleteAllCar")
	public void deleteAllCar(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			Map<String, String> params = new HashMap<String, String>();
			String u_id = request.getParameter("u_id");
			String token = request.getParameter("token");
			String c_ids = request.getParameter("c_ids");
			params.put("u_id", u_id);
			params.put("token", token);
			params.put("c_id", c_ids);
			if (checkService.checkToken(u_id, token, map) && checkService.checkParams(params, map)) {
				apiCarService.deleteAllCar(c_ids);
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "删除成功！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.write(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 获取我的购物车数量
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "getMyCarCount")
	public void getMyCarCount(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			Map<String, String> params = new HashMap<String, String>();
			String u_id = request.getParameter("u_id");
			String token = request.getParameter("token");
			String city_id = request.getParameter("city_id");
			params.put("u_id", u_id);
			params.put("token", token);
			params.put("city_id", city_id);
			if (checkService.checkToken(u_id, token, map)) {
				apiCarService.getMyCarCount(params, map);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.write(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 添加到购物车
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping(value = "addBuyCar")
	public void addBuyCar(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String userId = request.getParameter("userId");
			String goodId = request.getParameter("goodId");
			String productId = request.getParameter("productId");
			Integer count = Integer.parseInt(request.getParameter("count"));
			// String topicId = request.getParameter("topicId");
			// String createDate=apiCar.getCreate_date().substring(0, 10);
			// String hour=apiCar.getCreate_date().substring(11, 13);
			String currDate = DateTimeUtil.getTimeByStyle("yyyy-MM-dd");
			String currHour = DateTimeUtil.getTimeByStyle("HH");
			Map<String, Object> conditionMap = new HashMap<>();
			conditionMap.put("userId", userId);
			conditionMap.put("goodId", goodId);
			conditionMap.put("productId", productId);
			conditionMap.put("currDate", currDate);
			conditionMap.put("currHour", currHour);

			// apiCarService.removeOverDueGoods(userId, currDate, currHour);

			ApiCar apiCar = apiCarService.getApiCarByCondition(conditionMap);
			if (!Util.isNull(apiCar)) {
				apiCar.setCount(apiCar.getCount() + count);
				map = apiCarService.updCarCount(apiCar);
			} else {
				ApiCar car = new ApiCar();
				car.setU_id(userId);
				car.setGoods_id(Long.valueOf(goodId));
				car.setCount(count);
				car.setCreate_date(DateUtil.nowTimeToString());
				car.setProduct_id(Long.valueOf(productId));
				car.setPrice(Util.getBigDecimal(request.getParameter("price")));
				car.setStatus(0);
				// car.setTopic_id(topicId);
				map = apiCarService.addBuyCard(car);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 根据id删除购物车
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping(value = "delCarById")
	public void delCarById(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			apiCarService.updateCarStatusByCarId(request.getParameter("id"), "2");
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "删除成功！");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 根据用户清空购物车
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping(value = "delAllCarByUserId")
	public void delAllCarByUserId(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// apiCarService.delAllCarByUserId(request.getParameter("userId"));
			apiCarService.updateCarStatusByUserId(request.getParameter("userId"), "2");
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "删除成功！");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 修改购物车商品的数量
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping(value = "updCardCount")
	public void updCardCount(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			ApiCar apiCar = new ApiCar();
			apiCar.setId(Integer.parseInt(request.getParameter("id")));
			apiCar.setProduct_id(Long.valueOf(request.getParameter("projectId")));
			apiCar.setCount(Integer.parseInt(request.getParameter("count")));
			map = apiCarService.updCarCount(apiCar);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.MESSAGE, Utils.RESULT_RC_EXCEPTION);
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 查看我的购物车
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping(value = "seeMyCart")
	public void seeMyCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String userId = request.getParameter("userId");
			List<Map<String, Object>> list = apiCarService.seeMycart(userId);
			for (Map<String, Object> map2 : list) {
				map2.put("PAR_TYPE", Integer.parseInt(map2.get("PAR_TYPE").toString()));
				map2.put("STATUS", Integer.parseInt(map2.get("STATUS").toString()));
				map2.put("MARKET", map2.get("MARKET").toString());
				map2.put("IS_DELETED", Integer.parseInt(map2.get("IS_DELETED").toString()));
				map2.put("SORT", Integer.parseInt(map2.get("SORT").toString()));
				map2.put("COUNT", Integer.parseInt(map2.get("COUNT").toString()));
				// map2.put("TOPIC_ID",Integer.parseInt(map2.get("TOPIC_ID").toString()));
				map2.put("ID", Integer.parseInt(map2.get("ID").toString()));
				map2.put("IS_DELETE", Integer.parseInt(map2.get("IS_DELETE").toString()));
				map2.put("PROMOTION_TYPE", Integer.parseInt(map2.get("PROMOTION_TYPE").toString()));
				map2.put("GROUP_FLAG", Integer.parseInt(map2.get("GROUP_FLAG").toString()));
				map2.put("STORE", Integer.parseInt(map2.get("STORE").toString()));
			}

			// for (Map<String, Object> carMap : list) {
			// String topicId = carMap.get("TOPIC_ID").toString();
			// if
			// (apiT_orderService.checkProductStatus(carMap.get("PRODUCT_ID").toString(),
			// topicId)) {
			// carMap.put("isOn", 0);// 可以下单 进行中
			// } else {
			//
			// Date currDate =
			// DateTimeUtil.stringToDate(DateTimeUtil.getTimeByStyle("yyyy-MM-dd"));
			// int currHour =
			// Integer.parseInt(DateTimeUtil.getTimeByStyle("HH"));
			// ApiT_goods_topic goods_topic =
			// goods_topicService.getTopicByTopicId(topicId);
			// Date topicDate =
			// DateTimeUtil.stringToDate(goods_topic.getStart_date());
			// int topicStartHour =
			// Integer.parseInt(goods_topic.getStart_time().substring(0, 2));
			// // int
			// //
			// topicEndHour=Integer.parseInt(goods_topic.getEnd_time().substring(0,2));
			// int diff = DateTimeUtil.compareTwoDate(currDate, topicDate);
			// if ((diff == 0 && topicStartHour > currHour) || diff == 1) {
			// carMap.put("isOn", 2);// 不可以下单 即将开始
			// } else {
			// carMap.put("isOn", 1);// 不可以下单 已结束
			// }
			// }
			// }
			map.put("data", list);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "查询成功！");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 根据所选的购物车id 显示相关信息
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "showMyChose")
	public void showMyChose(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			List<String> cardIdlist = new ArrayList<>();
			String carIds = request.getParameter("carIds");
			String[] carIdArr = carIds.split(",");
			for (int i = 0; i < carIdArr.length; i++) {
				cardIdlist.add(carIdArr[i]);
			}
			List<ApiCar> list = apiCarService.showMyChose(cardIdlist);
			map.put("data", list);
			ApiAddress address = addressService.getAddressEnable(request.getParameter("userId"));
			map.put("address", address);

			String leftMoney = "0";
			ApiT_member member = memberService.getMemberById(request.getParameter("userId"));
			if (!Util.isNull(member) && !Util.isNull(member.getC_money())) {
				leftMoney = member.getC_money().toString();
			}
			map.put("memberLeftMoney", leftMoney);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "查询成功！");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		response.setCharacterEncoding("UTF-8");
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 清空实效商品
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "removeOverDueGoods")
	public void removeOverDueGoods(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String userId = request.getParameter("userId");
			String currentDate = DateTimeUtil.getTimeByStyle("yyyy-MM-dd");
			String currentHour = DateTimeUtil.getTimeByStyle("HH");
			apiCarService.removeOverDueGoods(userId, currentDate, currentHour);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "删除成功！");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

}
